/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package biofilter.util;

import java.util.StringTokenizer;
import java.text.ParseException;
/**
 *
 * @author Daniel Quest
 */
public class StringUtil {

    public StringUtil(){

    }

    public String[] splitOnSpaces(String line, int expectedElements) throws ParseException {
        return splitOnDelim(line, " ", expectedElements);
    }

    public String[] splitOnTab(String line, int expectedElements) throws ParseException {
        return splitOnDelim(line, "\t", expectedElements);
    }

    public String[] splitOnALLWhitepace(String line, int expectedElements) throws ParseException {
        return splitOnDelim(line, " \t\n\r\f", expectedElements);
    }

    public String[] splitOnDelim(String line, String delims, int expectedElements) throws ParseException  {
        int counter = 0;
        String cols[] = new String[expectedElements];
        StringTokenizer st = new StringTokenizer(line, delims);
        if (st.countTokens() == 0) throw new ParseException("StringUtil:splitOnDelim can not parse: " + line, 0);
        while (st.hasMoreTokens()){
            if(counter < expectedElements ){
                cols[counter] = st.nextToken();
                //System.err.println(cols[counter]);
            }
            if(counter >= expectedElements){
                cols[expectedElements -2] = cols[expectedElements -2] + " ";
                cols[expectedElements -2] = cols[expectedElements -2] + st.nextToken();
            }
            counter++;
        }
        return cols;

   }

      /**
       * ripOffStartToken:
       * takes any line and a token assumed to be the start of the line
       * returns line with the token trimmed off the front
       */
      public String ripOffStartToken (String line, String token) throws ParseException {
          if(line.startsWith(token))
            return line.substring(token.length()).trim();
          else{
              throw new ParseException(line + " : " + token , token.length()  );
          }
      }

      /**
       * ripOffEndToken:
       * takes any line and a token assumed to be the end of the line
       * returns line with the token trimmed off the end
       */
      public String ripOffEndToken (String line, String token) throws ParseException {
          if(line.endsWith(token))
            return line.substring(0, line.length() - token.length() ).trim();
          else{
              throw new ParseException(line + " : " + token , token.length()  );
          }
      }
   
}

